package net.my.msn.dao.impl;

import java.util.List;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import net.my.msn.dao.JpaImplTemplateDAO;
import net.my.msn.dao.UserDAO;
import net.my.msn.domain.User;
import net.my.msn.web.forms.Registration;

@Repository
public class UserDAOImpl extends JpaImplTemplateDAO<User, Long> implements
		UserDAO {

	public UserDAOImpl() {
		super(User.class);
	}

	@SuppressWarnings("unchecked")
	public List<User> find() {
		Query q = em.createNamedQuery("findAllUsers");
		return q.getResultList();
	}

	public User findByName(String username) {
		Query q = em.createNamedQuery("findByName").setParameter("username",
				username);
		User user = null;
		q.setMaxResults(1);
		@SuppressWarnings("unchecked")
		List<User> resultList = q.getResultList();
		if (resultList != null && !resultList.isEmpty())
			user = (User) resultList.get(0);
		return user;
	}

	public User findByEmail(String email) {
		User user = null;
		Query q = em.createNamedQuery("findByEmail").setParameter("email",
				email);
		q.setMaxResults(1);
		@SuppressWarnings("unchecked")
		List<User> resultList = q.getResultList();
		if (resultList != null && !resultList.isEmpty())
			user = (User) resultList.get(0);
		return user;
	}

	public boolean userCheck(Registration reg) {
		if ((findByName(reg.getUsername()) != null)
				|| (findByEmail(reg.getEmail()) != null))
			return false;
		return true;
	}

	public User findBySenderId(Long s_id) {
		Query q = em.createNamedQuery("findBySenderId").setParameter("s_id",
				s_id);
		q.setMaxResults(1);
		return (User) q.getSingleResult();
	}

}
